var express = require('express');
var Engine = require('tingodb')();
var morgan = require('morgan');
var bodyParser = require('body-parser');
var expressJwt = require('express-jwt');
var jwt = require('jsonwebtoken');
var cookieParser = require('cookie-parser')
var session = require('express-session')
var oracle = require('oracle');

var app = express();

var SECRET = 'this is the secret secret secret 12356';


app.use(cookieParser()) // required before session.
app.use(session({
  secret: 'schrodinger',
  saveUninitialized: true,
  resave: true
}))

app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({
  extended: true
})); // pull information from html in POST
app.use(bodyParser.json()); // pull information from html in POST

//######################
var routerApi2 = express.Router();
var routerLogin = express.Router();
var db = new Engine.Db('./database', {});
var configure = db.collection("configure");

// gestion de api2
app.use('/api2', expressJwt({
  secret: SECRET
}));

app.use('/api2', routerApi2);

routerApi2.param('collectionName', function(req, res, next, collectionName) {
  req.collection = db.collection(collectionName);
  return next();
})

routerApi2.get('/', function(req, res) {
  res.json({
    message: 'bienvenue sur l api2!'
  });
});

// find all
routerApi2.get('/collections/:collectionName', function(req, res, next) {
  req.collection.find({}).toArray(function(e, results) {
    if (e) return next(e);
    res.send(results);
  });
});
// find one
routerApi2.get('/collections/:collectionName/:id', function(req, res, next) {
  req.collection.findOne({
    _id: req.params.id
  }, function(e, result) {
    if (e) return next(e)
    res.send(result);
  });
});
// create
routerApi2.post('/collections/:collectionName', function(req, res, next) {
  req.collection.insert(req.body, {}, function(e, results) {
    if (e) return next(e);
    res.send(results[0]);
  });
});
// update
routerApi2.put('/collections/:collectionName/:id', function(req, res, next) {
  req.collection.update({
    _id: req.params.id
  }, req.body, {
    safe: true,
    multi: false
  }, function(e, result) {
    if (e) return next(e);
    res.send(result);
  });
});
// delete
routerApi2.delete('/collections/:collectionName/:id', function(req, res, next) {
  req.collection.remove({
    _id: req.params.id
  }, function(e, result) {
    if (e) return next(e)
    res.send((result === 1) ? {
      msg: 'success'
    } : {
      msg: 'error'
    });
  });
});

// set base selected in session
routerApi2.get('/setbase/:collectionName/:id', function(req, res, next) {
  var sess = req.session;
  console.log(req.params.id)
  req.collection.findOne({
    _id: req.params.id
  }, function(e, result) {
    if (e) return next(e)
    console.log(result);
    sess.selectedDatabase = result;
    res.send('OK');
  });
});

// set base selected in session
routerApi2.get('/graphes/:id', function(req, res, next) {
  var sess = req.session;
  res.send(sess.selectedDatabase);
});

// set base selected in session
routerApi2.get('/dbids', function(req, res, next) {
  var sess = req.session;
  var connectData = {
    hostname: sess.selectedDatabase.hostname,
    port: sess.selectedDatabase.port,
    database: sess.selectedDatabase.database, // System ID (SID)
    user: sess.selectedDatabase.user,
    password: sess.selectedDatabase.password
  };
  oracle.connect(connectData, function(err, connection) {
    if (err) {
      console.log("Error connecting to db:", err);
      return;
    }

    connection.execute("SELECT UNIQUE dbid, DB_NAME ||'-'||INSTANCE_NAME ||'('||dbid ||')' DBID_NAME FROM DBA_HIST_DATABASE_INSTANCE", [], function(err, results) {
      if (err) {
        console.log("Error executing query:", err);
        return;
      }

      console.log(results);
      res.send(results);
      connection.close(); // call only when query is finished executing
    });
  });
});

//######################

// gestion de login
app.use('/login', routerLogin);

routerLogin.param('collectionName', function(req, res, next, collectionName) {
  req.collection = db.collection(collectionName);

  return next();
})

routerLogin.get('/', function(req, res) {
  res.json({
    message: 'bienvenue sur l api login!'
  });
});

routerLogin.put('/:collectionName', function(req, res, next) {
  req.collection.findOne({
    username: req.body.username
  }, function(e, result) {
    if (e) return next(e)
    if (result == null) {
      res.send(401, 'Wrong user');
      return;
    }
    if (!(req.body.password === result.password)) {
      res.send(401, 'Wrong password');
      return;
    }
    var profile = {
      username: result.username,
      id: result._id
    };
    // We are sending the profile inside the token
    var token = jwt.sign(profile, SECRET
      /*, {
            expiresInMinutes: 60 * 5
        }*/
    );
    res.json({
      token: token
    });
  });
});

// find all
routerLogin.get('/:collectionName', function(req, res, next) {
  req.collection.find({}).toArray(function(e, results) {
    if (e) return next(e);
    res.send(results);
  });
});

// register user
routerLogin.post('/:collectionName', function(req, res) {
  req.collection.findOne({
    username: req.body.username
  }, function(e, result) {
    if (e) return next(e);
    if (result == null) {
      req.collection.insert(req.body, {}, function(e, results) {
        if (e) return next(e);
        res.send(200, 'Created');
      });
    } else {
      res.send(401, 'Already exist');
    }
  });
});

// delete user
routerLogin.delete('/:collectionName/:id', function(req, res, next) {
  req.collection.remove({
    _id: req.params.id
  }, function(e, result) {
    if (e) return next(e)
    res.send((result === 1) ? {
      msg: 'success'
    } : {
      msg: 'error'
    });
  });
});

app.listen(8082);
